package com.cmcc.driver.ui.main

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.entity.OrderDetail
import com.cmcc.driver.databinding.ActivityOrderRecordDetailBinding
import com.cmcc.driver.ui.base.BasicActivity
import com.cmcc.driver.ui.dialog.AppAlertDialog
import com.cmcc.driver.ui.main.viewmodel.OrderReceiveViewModel
import com.cmcc.driver.util.LocationUtil
import com.cmcc.shared.utils.TextViewUtil.setTextViewByLimit
import com.cmcc.shared.utils.TextViewUtil.setTextViewValue
import com.cmcc.shared.utils.clickWithTrigger
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.*
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback
import com.google.maps.android.PolyUtil


/**
 * Author: jiangxin
 * Date: 2019/11/6
 * Description: 记录
 */
@Route(path = DriverPath.ORDER_RECORD_DETAIL)
class OrderRecordDetailActivity : BasicActivity(), OnMapReadyCallback {


    private lateinit var mMap: GoogleMap
    private lateinit var binding: ActivityOrderRecordDetailBinding

    private var viewModel: OrderReceiveViewModel? = null
    private var orderModel: OrderDetail? = null

    private lateinit var bottomSheetBehavior: BottomSheetBehavior<ConstraintLayout>

    override fun onMapReady(googleMap: GoogleMap) {
        mMap = googleMap

//        val lat = orderModel?.startCoordinates?.longitude
//        val lng = orderModel?.startCoordinates?.longitude
//        val appointLoc = LatLng(lat ?: 0.0, lng ?: 0.0)
        val appointLoc = LocationUtil.getInstance().getCurrentLoc()
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(appointLoc, 15f))

        drawRoutes(googleMap)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        binding = DataBindingUtil.setContentView(
            this,
            R.layout.activity_order_record_detail
        )
        binding.appbar.toolbar.setNavigationOnClickListener { finish() }
        //把地图加到fragment layout去
        val mapFragment  = SupportMapFragment()
        supportFragmentManager.beginTransaction().replace(R.id.map, mapFragment).commit();
        mapFragment?.getMapAsync(this)

        bottomSheetBehavior = BottomSheetBehavior.from(binding.progress)

        viewModel = ViewModelProviders.of(this).get(OrderReceiveViewModel::class.java)

        val orderId = intent.getStringExtra("orderId")

        viewModel?.getOrderDetail(orderId ?: "")

        // 在onCreate 方法中  让它默认展开状态
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        binding.appbar.toolbar.setNavigationOnClickListener { finish() }

        binding.appbar.title.text = getString(R.string.record_detail_title)

        binding.appbar.profile.visibility = View.GONE


    }

    override fun initEvent(savedInstanceState: Bundle?) {
        super.initEvent(savedInstanceState)
        binding.appbar.profile.clickWithTrigger {
            ARouter.getInstance().build(DriverPath.DRIVER_PROFILE).navigation()
        }

        binding.contactPass.clickWithTrigger {
            AppAlertDialog(this).setContent(getString(R.string.if_you_need_call))
                .setNavigation(getString(R.string.cancel), null)
                .setPositive(getString(R.string.make_sure),
                    View.OnClickListener {
                        val data = Uri.parse("tel:"+orderModel?.passenger?.phone)
                        val intent = Intent(Intent.ACTION_DIAL, data)
                        startActivity(intent)
                    }).show()
        }

        binding.collapsingLayout.clickWithTrigger {
            when (bottomSheetBehavior.state) {
                BottomSheetBehavior.STATE_COLLAPSED -> {// 展开状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
                }
                BottomSheetBehavior.STATE_EXPANDED -> {//收起状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED
                }
            }
        }



        binding.collapsingLayout.clickWithTrigger {
            when (bottomSheetBehavior.state) {
                BottomSheetBehavior.STATE_COLLAPSED -> {//收起状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED

                    binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                }
                BottomSheetBehavior.STATE_EXPANDED -> {//展开状态
                    bottomSheetBehavior.state = BottomSheetBehavior.STATE_COLLAPSED

                    binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                }
            }
        }



        bottomSheetBehavior.setBottomSheetCallback(object : BottomSheetCallback() {
            override fun onStateChanged(bottomSheet: View, newState: Int) {
                when (bottomSheetBehavior.state) {
                    BottomSheetBehavior.STATE_COLLAPSED -> {//收起状态
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_collapsed)
                    }
                    BottomSheetBehavior.STATE_EXPANDED -> {//展开状态
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                        binding.collapsing.setBackgroundResource(R.drawable.ic_behavior_expanded)
                    }

                }
            }

            override fun onSlide(bottomSheet: View, slideOffset: Float) {}
        })
    }

    override fun initObserver(savedInstanceState: Bundle?) {
        super.initObserver(savedInstanceState)

        viewModel?.orderDetail?.observe(this, Observer { order ->
            orderModel = order

            binding.directions.directionStart.text = order?.startAddress
            binding.directions.directionEnd.text = order?.endAddress

            setTextViewByLimit(
                binding.textView2,
                order?.type == 1,
                getString(R.string.driver_real_time_order),
                getString(R.string.driver_reservation_order)
            )

            setTextViewByLimit(
                binding.options.textView3,
                order?.type == 1,
                getString(R.string.time_real_time),
                getString(R.string.order_create_time, order?.startTime)
            )

            setTextViewValue(
                this,
                binding.options.tunnel,
                R.string.order_tunnel,
                order?.tunnel?.name,
                getString(R.string.what_ever)
            )


            if(order.bountyFee==null){
                binding.options.tip.text = resources.getString(R.string.driver_tip)+"HK\$ "+"0.00"
            }
            else{
                binding.options.tip.text = resources.getString(R.string.driver_tip)+"HK\$ "+order.bountyFee.toString()+""
            }

            setTextViewValue(
                this,
                binding.options.station,
                R.string.order_station,
                if (order.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") null else order?.stationIndex,
                if (order.stationIndex.isNullOrEmpty() || order?.stationIndex == "0") getString(R.string.what_ever) else null
            )

            setTextViewValue(
                this,
                binding.options.remarks,
                R.string.order_remark,
                order?.remark,
                getString(R.string.none)
            )


            queryRoute()

        })

    }

    /**
     * 请求路线
     */
    private fun queryRoute() {
        viewModel?.getDirection(
            orderModel?.startCoordinates?.latitude.toString() + "," + orderModel?.startCoordinates?.longitude,
            orderModel?.endCoordinates?.latitude.toString() + "," + orderModel?.endCoordinates?.longitude
        )
    }


    /**
     * 绘制路线到谷歌地图
     */
    private fun drawRoutes(map: GoogleMap) {
        viewModel?.direction?.observe(this, Observer {
            val decodedPath = PolyUtil.decode(it) //来源Google Map Util
            val lineOptions = PolylineOptions()
            lineOptions.addAll(decodedPath) //添加路线
            lineOptions.color(Color.parseColor("#0AC6A2")) //线条设置
            lineOptions.jointType(JointType.ROUND)
            lineOptions.width(15f)
            map.clear()
            map.addPolyline(lineOptions)
            if (decodedPath.size > 2) {
                zoomRoute(map, decodedPath)
                map.addMarker(
                    MarkerOptions().position(decodedPath[0]).icon(
                        BitmapDescriptorFactory.fromResource(
                            R.drawable.ic_start_point
                        )
                    )
                )
                map.addMarker(
                    MarkerOptions().position(decodedPath[decodedPath.size - 1]).icon(
                        BitmapDescriptorFactory.fromResource(R.drawable.ic_end_point)
                    )
                )
                map.setOnCameraIdleListener { }
            }
        })
    }

    /**
     * Zooms a Route (given a List of LalLng) at the greatest possible zoom level.
     *
     *
     *
     *
     *
     *
     * @param googleMap: instance of GoogleMap
     * @param lstLatLngRoute: list of LatLng forming Route
     */
    private fun zoomRoute(googleMap: GoogleMap?, lstLatLngRoute: List<LatLng>?) {

        if (googleMap == null || lstLatLngRoute == null || lstLatLngRoute.isEmpty()) return

        val boundsBuilder = LatLngBounds.Builder()
        for (latLngPoint in lstLatLngRoute)
            boundsBuilder.include(latLngPoint)

        val routePadding = 100
        val latLngBounds = boundsBuilder.build()

        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, routePadding))
    }

}